package com.voc.im.controller.account;

import com.voc.im.bean.Account;
import com.voc.im.model.AccountModel;
import io.datafx.controller.FXMLController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.function.UnaryOperator;

@FXMLController("/fxml/account_register.fxml")
public class AccountRegisterController {

    @FXML
    private Button btnGoLogin, btnConfirmRegister;

    @FXML
    private TextField fieldNickname, fieldInviter;

    @FXML
    private PasswordField fieldPassword, fieldPasswordSure;

    @Inject
    private AccountModel accountModel;

    @PostConstruct
    public void init() throws Exception {
        btnGoLogin.setOnAction(this::onActionGoLogin);

        btnConfirmRegister.setOnAction(this::onActionConfirmRegister);

        btnGoLogin.focusedProperty().addListener((observable, oldValue, newValue) -> {

        });

        fieldPassword.setTextFormatter(new TextFormatter<String>(this::unaryOperatorPassword));
        fieldPasswordSure.setTextFormatter(new TextFormatter<String>(this::unaryOperatorPassword));
    }

    /**
     * 去登录点击事件
     */
    private void onActionGoLogin(ActionEvent event) {
        accountModel.setActionProperty("login");
    }

    /**
     * 提交注册表单
     */
    private void onActionConfirmRegister(ActionEvent event) {
        String nickname = fieldNickname.getText();
        String password = fieldPassword.getText();
        String passwordSure = fieldPasswordSure.getText();
        String inviter = fieldInviter.getText();
        if (nickname.isEmpty()) {
            return;
        }
        if (password.isEmpty()) {
            return;
        }
        if (password.length() < 6) {
            return;
        }
        if (passwordSure.isEmpty()) {
            return;
        }
        if (!password.equals(passwordSure)) {
            return;
        }
        if (inviter.isEmpty()) {
            return;
        }
        Account.Register register = new Account.Register(nickname, password, inviter);
        accountModel.setObjectProperty(new Account<>(register));
        accountModel.setActionProperty("status");
    }

    /**
     * 正则表达验证，密码框只允许输入数字
     */
    private TextFormatter.Change unaryOperatorPassword(TextFormatter.Change change) {
        if (change.getText().matches("^[0-9]*$")) {
            return change;
        }
        return null;
    }

}
